﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.Diagnostics;

namespace Common.Com
{
    public class RegeditHelper
    {
        /// <summary>
        /// 读取注册表键值
        /// </summary>
        /// <param name="subKey"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public string GetRegistData(string subKey, string name)
        {
            string registData;
            RegistryKey hkml = Registry.LocalMachine;
            RegistryKey software = hkml.OpenSubKey("SOFTWARE", true);
            RegistryKey aimdir = software.OpenSubKey(subKey, true);
            registData = aimdir.GetValue(name).ToString();
            return registData;
        }
        /// <summary>
        /// 写入注册表值
        /// </summary>
        /// <param name="subKey"></param>
        /// <param name="name"></param>
        /// <param name="tovalue"></param>
        public void WriteRegedit(string subKey, string name, string tovalue)
        {
            RegistryKey hklm = Registry.LocalMachine;
            RegistryKey software = hklm.OpenSubKey("SOFTWARE", true);
            RegistryKey aimdir = software.CreateSubKey(subKey);
            aimdir.SetValue(name, tovalue);
        }
        /// <summary>
        /// 删除注册表值
        /// </summary>
        /// <param name="subKey"></param>
        public void DeleteRegist(string subKey)
        {
            RegistryKey hkml = Registry.LocalMachine;
            RegistryKey software = hkml.OpenSubKey("SOFTWARE", true);
            software.DeleteSubKey(subKey);
        }
        /// <summary>
        /// 判断注册值是否存在
        /// </summary>
        /// <param name="subKey"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool IsRegeditExit(string subKey, string name)
        {
            bool _exit = false;
            try
            {
                string[] subkeyNames;
                RegistryKey hkml = Registry.LocalMachine;
                RegistryKey software = hkml.OpenSubKey("SOFTWARE", true);
                RegistryKey aimdir = software.OpenSubKey(subKey, true);
                subkeyNames = aimdir.GetValueNames();
                foreach (string keyName in subkeyNames)
                {
                    if (keyName == name)
                    {
                        _exit = true;
                        return _exit;
                    }
                }
            }
            catch
            { }
            return _exit;
        }
    }
}
